/*
 * Name: Joon Ho Cho
 * Date: 10/24/2008
 * Course: 15-437
 */
package scheduler.controller;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;


import org.mybeans.dao.DAOException;
import org.mybeans.forms.FormBeanFactory;

import scheduler.databean.User;
import scheduler.formbean.RegisterForm;
import scheduler.model.Model;
import scheduler.model.UserDao;



public class RegisterAction extends Action {
	private FormBeanFactory<RegisterForm> formBeanFactory = FormBeanFactory.getInstance(RegisterForm.class,"<>\"");

	private UserDao userDAO;
	
	public RegisterAction(Model model) {
		userDAO = model.getUserDao();
	}

	public String getName() { return "register.do"; }

    public String perform(HttpServletRequest request) {
    	RegisterForm form = formBeanFactory.create(request);
    	
        // Set up the request attributes (the errors list and the form bean so
        // we can just return to the jsp with the form if the request isn't correct)
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);
        request.setAttribute("form",form);

        // If no params were passed, return with no errors so that the form will be
        // presented (we assume for the first time).
        if (!form.isPresent()) {
            return "register.jsp";
        }

        // Any validation errors?
        errors.addAll(form.getValidationErrors());
        if (errors.size() != 0) {
            return "register.jsp";
        }

        // Create the user bean
        User user = new User(form.getEmail());
        user.setPassword(form.getPassword());
        try {
        	userDAO.create(user);
            // Set up user list for nav bar
    		request.setAttribute("registeredUsers",userDAO.getAll());
        } catch (DAOException e) {
        	errors.add(e.getMessage());
        	return "register.jsp";
        }
        
		// Attach (this copy of) the user bean to the session
        HttpSession session = request.getSession(false);
        session.setAttribute("user",user);

        // After successful registration (and login) send to...
        String redirectTo = (String) session.getAttribute("redirectTo");
        if (redirectTo != null) return redirectTo;
        
        // If redirectTo is null, redirect to the "manage" action
		String webapp = request.getContextPath();
		return webapp + "/manage.do";
    }
}
